//
//  ConGoodsManagerController.m
//  Shengzhuli
//
//  Created by FXGuo on 17/3/26.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConGoodsManagerController.h"
#import "ShoppingMallsCell.h"
#import "SZLSellerAddGoodsViewController.h"
#import "SZLAccountHelper.h"
#import "BusinessNetwork.h"
#import <MJRefresh.h>
#import "MBProgressHUD+MJ.h"
#import "SingleListTableViewCell.h"
#import "ConSingleDetailController.h"
#import "MyScrollView.h"

@interface ConGoodsManagerController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic,weak) UIScrollView *scrool;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *publicGoods;
@property (nonatomic,assign) NSInteger pCurPage;
@property (nonatomic,weak) UISegmentedControl *seg;

@property (nonatomic,strong) UITableView *completeTable;
@property (nonatomic,strong) NSMutableArray *completeGoods;
@property (nonatomic,assign) NSInteger cCurPage;

@property (nonatomic,assign) BOOL isFirstComplete;//是否第一次点击售出

@end

@implementation ConGoodsManagerController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setNavi];
    [self setTableViews];
    self.pCurPage = 1;
    self.cCurPage = 1;
    self.isFirstComplete = YES;
    [self getPublicGoodsList];
}
- (void)setNavi
{
//    CGSize imageSize = CGSizeMake(320,64);
//    UIGraphicsBeginImageContextWithOptions(imageSize,0, [UIScreen mainScreen].scale);
//    [[UIColor whiteColor] set];
//    UIRectFill(CGRectMake(0,0, imageSize.width, imageSize.height));
//    UIImage *pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    [self.navigationController.navigationBar setBackgroundImage:pressedColorImg forBarMetrics:UIBarMetricsDefault];
    
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:@[@"已发布",@"已售出"]];
    seg.frame = CGRectMake(0, 0, 200, 35);
    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor blackColor];
    [seg setTitleTextAttributes:@{NSFontAttributeName:Font(16)} forState:UIControlStateNormal];
    [seg addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    self.seg = seg;
    self.navigationItem.titleView = seg;
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
//    [btn setImage:GetImage(@"add_white") forState:UIControlStateNormal];
    [btn setTitle:@"＋" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(publicClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,[[UIBarButtonItem alloc]initWithCustomView:btn]];
}
- (void)valueChanged:(UISegmentedControl *)seg
{
    self.scrool.contentOffset = CGPointMake(ScreenW*seg.selectedSegmentIndex, 0);
    if (self.isFirstComplete) {
        [self getCompleteSingle];
    }
    self.isFirstComplete = NO;
}
- (void)publicClick
{
    SZLSellerAddGoodsViewController *mgrVc = [[SZLSellerAddGoodsViewController alloc]init];
    mgrVc.type = SellerGoodsTypeAdd;
    __WEAK
    mgrVc.successBlock = ^{
        self.pCurPage = 1;
        [weakSelf.publicGoods removeAllObjects];
        [self getPublicGoodsList];
    };
    [self.navigationController pushViewController:mgrVc animated:YES];
}
- (void)setTableViews
{
    UIScrollView *scrool = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    scrool.contentSize = CGSizeMake(ScreenW*2, ScreenH);
    scrool.pagingEnabled = YES;
    scrool.bounces = NO;
    scrool.delegate = self;
    scrool.showsHorizontalScrollIndicator = NO;
    scrool.delaysContentTouches = NO;
    scrool.scrollEnabled = NO;
    self.scrool = scrool;
    [self.view addSubview:scrool];
    [scrool addSubview:self.tableView];
    [scrool addSubview:self.completeTable];
}
//不让scrollview滑动 与侧滑删除冲突
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView == self.scrool) {
//        NSInteger page = (NSInteger)(scrollView.contentOffset.x / scrollView.width + 0.5);
//        self.seg.selectedSegmentIndex = page;
//        if (self.isFirstComplete) {
//            [self getCompleteSingle];
//        }
//        self.isFirstComplete = NO;
//    }
//}
#pragma mark - Table view data delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return 120;
    }
    return 183;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return self.publicGoods.count;
    }
    return self.completeGoods.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        ShoppingMallsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ShoppingMallsCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isSeller = YES;
        cell.model = self.publicGoods[indexPath.section];
        return cell;
    }
    SingleListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SingleListTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.clipsToBounds = YES;
    cell.isSeller = YES;
    cell.model = self.completeGoods[indexPath.section];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        SZLSellerAddGoodsViewController *mgrVc = [[SZLSellerAddGoodsViewController alloc]init];
        mgrVc.type = SellerGoodsTypeShow;
        NormalShopGoodsModel *model = self.publicGoods[indexPath.section];
        mgrVc.productNumber = model.productNo;
        __WEAK
        mgrVc.successBlock = ^{
            weakSelf.pCurPage = 1;
            [weakSelf getPublicGoodsList];
        };
        [self.navigationController pushViewController:mgrVc animated:YES];
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ConSingleDetailController *detailVc = [[ConSingleDetailController alloc]init];
    detailVc.isSeller = YES;
    detailVc.listModel = self.completeGoods[indexPath.section];
    __WEAK
    detailVc.successBlock = ^{
        weakSelf.cCurPage = 1;
        [weakSelf getCompleteSingle];
    };
    [self.navigationController pushViewController:detailVc animated:YES];
    
}
#pragma mark ------tableview侧拉-----------------------------
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return YES;
    }
    return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        [self removeGoods:indexPath.section];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"下架";
}
//获取已发布商品列表
- (void)getPublicGoodsList
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"pageNo"]  = @(self.pCurPage);
    [self showWaiter];
    [BusinessNetwork getShopGoodsListWithParame:params response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        if (success) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self hideNoDataLab];
            self.tableView.mj_footer.hidden = (lists.count < 20);
            if (self.pCurPage == 1) {
                if (lists.count == 0) {
                    [self showNoDataLab:self.tableView range:CGRectMake(0, self.tableView.height*0.5-10, ScreenW, 20) title:@"暂无商品"];
                    return ;
                }
                [self.publicGoods removeAllObjects];
            }else{
                if (lists.count == 0) return;
            }
            [self.publicGoods addObjectsFromArray:lists];
            [self.tableView reloadData];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
//获取已售出商品列表
- (void)getCompleteSingle
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"token"] = [SZLAccountHelper shareInstance].token;
    params[@"pageNo"]  = @(self.pCurPage);
    [self showWaiter];
    [BusinessNetwork getSellGoodsListWithParame:params response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        if (success) {
            [self.completeTable.mj_header endRefreshing];
            [self.completeTable.mj_footer endRefreshing];
            [self hideNoDataLab];
            self.completeTable.mj_footer.hidden = (lists.count < 20);
            if (self.pCurPage == 1) {
                if (lists.count == 0) {
                    [self showNoDataLab:self.completeTable range:CGRectMake(ScreenW, self.completeTable.height*0.5-10, ScreenW, 20) title:@"暂无商品"];
                    return ;
                }
                [self.completeGoods removeAllObjects];
            }else{
                if (lists.count == 0) return;
            }
            [self.completeGoods addObjectsFromArray:lists];
            [self.completeTable reloadData];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)removeGoods:(NSInteger)index
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    NormalShopGoodsModel *model = self.publicGoods[index];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNo"] = model.productNo;
    [self showClearBgWaiter];
    [BusinessNetwork removewGoodsWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [self.publicGoods removeObjectAtIndex:index];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationTop];
            if (self.publicGoods.count == 0) {
                [self showNoDataView:self.tableView.frame title:@"暂无商品"];
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    }];
}
- (NSMutableArray *)publicGoods
{
    if (!_publicGoods) {
        _publicGoods = [NSMutableArray array];
    }
    return _publicGoods;
}
- (NSMutableArray *)completeGoods
{
    if (!_completeGoods) {
        _completeGoods = [NSMutableArray array];
    }
    return _completeGoods;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        _tableView.sectionFooterHeight = 0.01;
        _tableView.sectionHeaderHeight = 10;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ShoppingMallsCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ShoppingMallsCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.pCurPage = 1;
            [self getPublicGoodsList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.pCurPage++;
            [self getPublicGoodsList];
        }];
    }
    return _tableView;
}
- (UITableView *)completeTable
{
    if (!_completeTable) {
        _completeTable = [[UITableView alloc] initWithFrame:CGRectMake(ScreenW, 0, ScreenW, ScreenH-SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _completeTable.dataSource = self;
        _completeTable.delegate = self;
        _completeTable.sectionHeaderHeight = 10;
        _completeTable.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        _completeTable.sectionFooterHeight = 0.01;
        _completeTable.rowHeight = 183;
        _completeTable.tableFooterView = [[UIView alloc]init];
        [_completeTable registerNib:[UINib nibWithNibName:NSStringFromClass([SingleListTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SingleListTableViewCell class])];
        _completeTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.cCurPage = 1;
            [self getCompleteSingle];
        }];
        _completeTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.cCurPage++;
            [self getCompleteSingle];
        }];
        _completeTable.mj_footer.hidden = YES;
    }
    return _completeTable;
}

@end
